﻿var EnumPrefix = "Enum_";

var Enum_OrderStatus = [
{ text: "未完成", value: 0, description: "Unfinished" },
{ text: "已完成", value: 1, description: "Accomplished" },
{ text: "取消的", value: 2, description: "Canceled" }
];

var Enum_DishType = [
{ text: "未分类", value: 0, description: "None" },
{ text: "冷菜", value: 1, description: "ColdDish" },
{ text: "热菜", value: 2, description: "HotDish" },
{ text: "汤", value: 3, description: "Soup" },
{ text: "甜点", value: 4, description: "Dessert" },
{ text: "饮料", value: 5, description: "Drink" },
{ text: "主食", value: 6, description: "StapleFood" }
];

var Enum_OrderedDishStatus = [
{ text: "待制作", value: 0, description: "WaitForCooking" },
{ text: "待上桌", value: 1, description: "ToServing" },
{ text: "已上桌", value: 2, description: "Served" },
{ text: "已取消", value: 3, description: "Canceled" }
];

var ViewIds = { edit: "editView", list: "listView", 
detail: "detailView", loading: "loadingView",
info: "infoView"
};

var RESOURCE = {
requestErrorMsg:"发生错误，请刷新页面。",
detailTitle:"详情",
detailLink:"查看",
okBtn:"OK"
};

var Mobi = {};

function viewDocReady() {
    if (typeof (outputData) == 'undefined') return;

    Mobi.listData = outputData;

    $('.title').attr("innerText", outputData.caption);

    switchView(ViewIds.list);

    var cols = [];
    var indexViewDetail = -1;
    if (outputData.canViewDetail) {
        indexViewDetail = cols.length;
        cols.push(null);
    }

    var primaryKey;
    for (var index = 0, len = outputData.columns.length; index < len; index++) {
        var column = outputData.columns[index];
        if (column.isPrimaryKey) {
            primaryKey = column.field;
        }

        if (column.hidden) {
            continue;
        }

        var col = { field: column.field, title: column.title, width: column.width };
        if (column.isDateTime) {
            col.render = function (r, tr) {
                var value = r[this.field];
                return date2String(convertDate(value));
            }
        }
        else if (column.enumType) {
            col.enumObject = eval(EnumPrefix + column.enumType);
            col.render = function (r, tr) {
                var enumObj = this.enumObject;
                if (typeof(enumObj) == 'undefined') {
                    return r;
                }
                var value = r[this.field];
                if (enumObj[value] != null && enumObj[value].value == value) {
                    return enumObj[value].text;
                }

                for (var enumIndex = 0, enumLen = enumObj.length; enumIndex < enumLen; enumIndex++) {
                    if (enumObj[enumIndex].value == value) {
                        return enumObj[enumIndex].text;
                    }
                }

                return r;
            }
        }

        cols.push(col);
    }

    if (primaryKey && indexViewDetail >= 0) {
        Mobi.primaryKey = primaryKey;
        var col = { field: primaryKey, title: RESOURCE.detailTitle, width: "40px" };
        col.render = function (r, tr) {
            var value = r[this.field];
            var renderStr = "<div onclick=\"viewDetail(" + value + ")\" class=\"customLink\">" 
            + RESOURCE.detailLink + "</div>";
            return renderStr;
        };
        cols[indexViewDetail] = col;
    }


    if (outputData.width) {
        $('.view').css("width", outputData.width);
    }

    if (outputData.height) {
        $('.view').css("height", outputData.height);
    }

    $('.view').mac('grid', {
        cols: cols,
        loader: {
            url: outputData.source,
            params: { pageNo: outputData.pageNo, pageSize: outputData.pageSize },
            autoLoad: true
        },
        pagerLength: 10
    });
};

function viewDetail(id) {
    if(!Mobi.primaryKey || !Mobi.listData.canViewDetail){
        return;
    }

    var loadingId = ViewIds.loading;
    switchView(loadingId);
    var url = Mobi.listData.source + "?" + Mobi.primaryKey + "=" + id;
    $.ajax({ processData : false,
    error : processError,
    success : viewDetailSuccess,
    //timeout : 30000,
    url :url
    });
};

function viewDetailSuccess(dataStr) {
    var data = null;
    try
    {
        eval("var tempData = " + dataStr);
        data = tempData;
    }
    catch(ex)
    {
        processError();
        return;
    }

    if (!data || !data.data || !data.data.list || !data.data.list.length) {
        processError();
        return;
    }

    if (!data.success) {
        processError(data.error);
        return;
    }

    var viewId = ViewIds.detail;
    var itemData = data.data.list[0];

    var output = new StringBuilder();
    var columns = Mobi.listData.columns;
    for (var index = 0, len = columns.length; index < len; index++) {
        var column = columns[index];
        var colData = itemData[column.field];
        output.append("<div>")
        .append(column.title)
        .append("</div>")
        .append("<div style='color:green'>");

        if (column.isDateTime) {
            output.append(date2String(convertDate(colData)));
        }
        else if (column.isImage) {
            output.append("<img src=\"")
            .append(colData ? "" : colData)
            .append("\" />");
        }
        else {
            output.append(colData ? colData : "");
        }

        output.append("</div>");
    }


    var detailViewer = $("#" + viewId);

    var divContentId = "divContentId";
    if ($("#" + divContentId).length == 0) {
        detailViewer.append("<div id='divContentId'></div>");
    }

    var divContent = $("#" + divContentId);
    divContent.attr("innerText", "");
    divContent.append(output.toString());

    var btnDetailOKId = "btnDetailOK";
    if ($("#" + btnDetailOKId).length == 0) {
        detailViewer.append("<input type=\"button\" value=\"" + RESOURCE.okBtn
        + "\" id=\"" + btnDetailOKId + "\"/>");
        $("#" + btnDetailOKId).bind("click", function () {
            switchView(ViewIds.list);
        });
    }

    switchView(viewId);
};

function processError(e) {
    var id = ViewIds.info;
    var error = RESOURCE.requestErrorMsg;
    if (e != null) {
        error += "\r\n" + e;
    }

    $("#" + id).attr(error);
    switchView(id);
};

function switchView(id) {
    for (var view in ViewIds) {
        $("#" + ViewIds[view]).css("display", "none");
    }

    $("#" + id).css("display", "block");
};

function convertDate(jsondate) {
    jsondate = jsondate.replace("/Date(", "").replace(")/", "");
    if (jsondate.indexOf("+") > 0) {
        jsondate = jsondate.substring(0, jsondate.indexOf("+"));
    }
    else if (jsondate.indexOf("-") > 0) {
        jsondate = jsondate.substring(0, jsondate.indexOf("-"));
    }

    return new Date(parseInt(jsondate, 10));
};

function date2String(date) {
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return date.getFullYear() + "-" + month + "-" + currentDate + " " + date.getHours() + ":" + date.getMinutes();
};

function StringBuilder(s) {
    this._array = [];
    if (s != null) {
        _array.push(s);
    }
};

StringBuilder.prototype.append = function (s) {
    if (s != null) {
        this._array.push(s);
    }
    return this;
};

StringBuilder.prototype.toString = function () {
    return this._array.join("");
};